import { createRouter, createWebHistory } from 'vue-router'
import RoutesConfig from './config'
import useRouterStore from '../store/useRouterStore'
import useUserStore from '../store/useUserStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/login',
            component: () => import('../views/Login.vue')
        },
        {
            path: '/mainbox',
            name: 'mainbox',
            component: () => import('../views/MainBox.vue')
        },
        {
            path: '/:pathMatch(.*)*',
            component: () => import('../views/404.vue')
        }
    ]
})
//路由拦截
router.beforeEach((to, from, next) => {
    //开启进度条
    NProgress.start()
    const { isGetterRouter } = useRouterStore()
    const {user} = useUserStore()
    if (to.path === "/login") {
        next()
    } else {
        if (!user.role) {
            next({
                path: '/login'
            })
        } else {
            //判断是否第一次加载路由，是就先动态添加路由，再跳转到该路由
            if (!isGetterRouter) {
                // console.log('router',router);
                // if(router.options.routes.length!==0){
                //     router.removeRoute()
                // }
                //权限管理
                ConfigRouter()
                next({
                    path: to.fullPath
                })
            } else {
                next()
            }
        }
    }
})
router.afterEach(()=>{
    //结束进度条
    NProgress.done()
})
const ConfigRouter = () => {
    const { changeRouter } = useRouterStore()
    router.addRoute({
        path:"/mainbox",
        name:"mainbox",
        component:()=>import("../views/MainBox.vue")
    })
    RoutesConfig.forEach(item => {
        // console.log(item);
        //动态添加路由(先进行权限匹配)
        console.log(item);
        checkPermission(item) && router.addRoute("mainbox", item)
    })
    //加重定向
    router.addRoute('mainbox', {
        path: "/",
        redirect: "/index"
    })
    //404匹配
    router.addRoute("mainbox", {
        path: '/:pathMatch(.*)*',
        name: 'not fount',
        component: () => import('../views/404.vue')
    })
    //改变状态
    changeRouter(true)
}
//根据后端返回的数组，判断路径是否存在(这里模拟数组)
const checkPermission = ({path}) => {
    const store = useUserStore()
    const {user:{role:{rights}}} = useUserStore()
    return store.user.role.rights.includes(path)
}
export default router